package com.ruoyi.search.controller;

import cn.easyes.core.biz.PageInfo;
import cn.easyes.core.conditions.LambdaEsQueryWrapper;
import com.ruoyi.common.dtos.ResponseResult;
import com.ruoyi.common.enums.AppHttpCodeEnum;
import com.ruoyi.common.satoken.utils.LoginHelper;
import com.ruoyi.search.domain.SearchArticleModel;
import com.ruoyi.search.domain.SearchArticleVo;
import com.ruoyi.search.domain.UserSearchDto;
import com.ruoyi.search.esmapper.SearchArticleMapper;
import com.ruoyi.search.mapper.ApArticleMapper;
import com.ruoyi.search.service.ApUserSearchService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@ConditionalOnProperty(value = "easy-es.enable", havingValue = "true")
@RestController
@RequestMapping
@RequiredArgsConstructor
public class ArticleSearchController {

    private final ApArticleMapper apArticleMapper;

    private final SearchArticleMapper searchArticleMapper;

    private final ApUserSearchService apUserSearchService;

    @PostMapping("/api/v1/article/search/search")
    public ResponseResult search(@RequestBody UserSearchDto dto) throws IOException {
        //todo 1.校验参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        //异步调用 保存搜索记录
        //Long userId = LoginHelper.getUserId();
        //if(userId != null){
        //由于设置了白名单，所以里面获取任何权限相关操作包括获取用户，token等都会报异常，所以用户id填写0L
            apUserSearchService.insert(dto.getSearchWords(), 0L);
        //}



        //todo 2.1 封装关键字搜索条件,小于min_behot_time
        LambdaEsQueryWrapper<SearchArticleVo> wrapper = new LambdaEsQueryWrapper<>();
        wrapper
            .lt(SearchArticleVo::getPublishTime,dto.getMinBehotTime())
            .and(w->w.like(SearchArticleVo::getTitle, dto.getSearchWords()).or().like(SearchArticleVo::getContent,dto.getSearchWords()));

        //todo 2.2. 分页查询
        //wrapper.size(dto.getPageSize());
        wrapper.orderByDesc(SearchArticleVo::getId);
        PageInfo<SearchArticleVo> searchArticleVoPageInfo = searchArticleMapper.pageQuery(wrapper, 0, dto.getPageSize());
        return ResponseResult.okResult(searchArticleVoPageInfo.getList());
    }

    @GetMapping("/api/v1/article/search/init")
    public ResponseResult init() throws IOException {
        //1.查询所有符合条件的文章数据
        List<SearchArticleVo> searchArticleVos = apArticleMapper.loadArticleList();

        for (SearchArticleVo searchArticleVo : searchArticleVos) {
            searchArticleMapper.insert(searchArticleVo);
        }
        return ResponseResult.okResult(200,"初始化成功！");
    }
}
